{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第1篇：pandas入门及Series介绍"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第1部分：Pandas概览"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas 是 Python 的核心数据分析支持库，提供了快速、灵活、明确的数据结构，旨在简单、直观地处理关系型、标记型数据。Pandas 的目标是成为 Python 数据分析实践与实战的必备高级工具，其长远目标是成为最强大、最灵活、可以支持任何语言的开源数据分析工具。经过多年不懈的努力，Pandas 离这个目标已经越来越近了。\n",
    "\n",
    "**Pandas 适用于处理以下类型的数据：**\n",
    "\n",
    "- 与 SQL 或 Excel 表类似的，含异构列的表格数据;\n",
    "- 有序和无序（非固定频率）的时间序列数据;\n",
    "- 带行列标签的矩阵数据，包括同构或异构型数据;\n",
    "- 任意其它形式的观测、统计数据集, 数据转入 Pandas 数据结构时不必事先标记。\n",
    "Pandas 的主要数据结构是 Series（一维数据）与 DataFrame（二维数据），这两种数据结构足以处理金融、统计、社会科学、工程等领域里的大多数典型用例。对于 R 用户，DataFrame 提供了比 R 语言 data.frame 更丰富的功能。Pandas 基于 NumPy 开发，可以与其它第三方科学计算支持库完美集成。\n",
    "\n",
    "**Pandas 就像一把万能瑞士军刀，下面仅列出了它的部分优势：**\n",
    "\n",
    "- 处理浮点与非浮点数据里的缺失数据，表示为 NaN；\n",
    "- 大小可变：插入或删除 DataFrame 等多维对象的列；\n",
    "- 自动、显式数据对齐：显式地将对象与一组标签对齐，也可以忽略标签，在 Series、DataFrame 计算时自动与数据对齐；\n",
    "- 强大、灵活的分组（group by）功能：拆分-应用-组合数据集，聚合、转换数据；\n",
    "- 把 Python 和 NumPy 数据结构里不规则、不同索引的数据轻松地转换为 DataFrame 对象；\n",
    "- 基于智能标签，对大型数据集进行切片、花式索引、子集分解等操作；\n",
    "- 直观地合并（merge）、**连接（join）**数据集；\n",
    "- 灵活地重塑（reshape）、**透视（pivot）**数据集；\n",
    "- 轴支持结构化标签：一个刻度支持多个标签；\n",
    "- 成熟的 IO 工具：读取文本文件（CSV 等支持分隔符的文件）、Excel 文件、数据库等来源的数据，利用超快的 HDF5 格式保存 / 加载数据；\n",
    "- 时间序列：支持日期范围生成、频率转换、移动窗口统计、移动窗口线性回归、日期位移等时间序列功能。\n",
    "这些功能主要是为了解决其它编程语言、科研环境的痛点。处理数据一般分为几个阶段：数据整理与清洗、数据分析与建模、数据可视化与制表，Pandas 是处理数据的理想工具。\n",
    "\n",
    "**其它说明：**\n",
    "\n",
    "- Pandas 速度很快。Pandas 的很多底层算法都用 Cython 优化过。然而，为了保持通用性，必然要牺牲一些性能，如果专注某一功能，完全可以开发出比 Pandas 更快的专用工具。\n",
    "- Pandas 是 statsmodels 的依赖项，因此，Pandas 也是 Python 中统计计算生态系统的重要组成部分。\n",
    "- Pandas 已广泛应用于金融领域。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第2部分：数据结构"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pandas两大核心数据结构：**Series**和**DataFrame**。 \n",
    "\n",
    "|维数\t  |  名称      |             描述       |  数据表 |\n",
    "| :--:  |  :---:     |       :-------:          | :---:  |\n",
    "|  1   |  Series    |    带标签的一维同构数组      |  一列或一行 |\n",
    "|  2   |\tDataFrame|\t带标签的，大小可变的，二维异构表|  一个sheet表或一个table|\n",
    "\n",
    "- Series是一种一维数据结构，每一个元素都带有一个索引，其中索引可以为数字或字符串。其基本数据结构为索引列和数据列。\n",
    "- Dataframe是一种二维数据结构，数据以表格形式（与excel类似）存储，有对应的行和列。其基本数据结构为索引列和多列数据，即Dataframe的由多个Series构成。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas 数据结构就像是低维数据的容器。比如，DataFrame 是 Series 的容器，Series 则是标量的容器。使用这种方式，可以在容器中以字典的形式插入或删除对象。\n",
    "\n",
    "此外，通用 API 函数的默认操作要顾及时间序列与截面数据集的方向。多维数组存储二维或三维数据时，编写函数要注意数据集的方向，这对用户来说是一种负担；如果不考虑 C 或 Fortran 中连续性对性能的影响，一般情况下，不同的轴在程序里其实没有什么区别。Pandas 里，轴的概念主要是为了给数据赋予更直观的语义，即用“更恰当”的方式表示数据集的方向。这样做可以让用户编写数据转换函数时，少费点脑子。\n",
    "\n",
    "处理 DataFrame 等表格数据时，index（行）或 columns（列）比 axis 0 和 axis 1 更直观。用这种方式迭代 DataFrame 的列，代码更易读易懂："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**大小可变和数据复制**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas 所有数据结构的值都是可变的，但数据结构的大小并非都是可变的，比如，Series 的长度不可改变，但 DataFrame 里就可以插入列。\n",
    "\n",
    "Pandas 里，绝大多数方法都不改变原始的输入数据，而是复制数据，生成新的对象。 一般来说，原始输入数据不变更稳妥。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 相关模块导入"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 查看pandas版本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1.1.3'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数据类型介绍\n",
    "Pandas 的数据类型是指某一列的里所有的数据的共性，如果全是数字那么就是类型数字型，其中一个不是数据那么就没法是数字型了。我们知道 Pandas 里的一列可以由 NumPy 数组组成，事实上大多 NumPy 的数据类型就是 Pandas 的类型，Pandas 也会有自己特有的数据类型。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 主要的数据类型\n",
    "\n",
    "- float\n",
    "- int\n",
    "- bool\n",
    "- datetime64[ns]\n",
    "- datetime64[ns, tz]\n",
    "- timedelta64[ns]\n",
    "- timedelta[ns]\n",
    "- category\n",
    "- object\n",
    "- string 新功能，还在实验阶段\n",
    "\n",
    "默认的数据类型是 int64 和 float64，文字类型是 object。\n",
    "\n",
    "和 python、NumPy 类型的对应关系：\n",
    "\n",
    "| Pandas 类型    | Python 类型  | NumPy类型                                                    | 使用场景                   |\n",
    "| -------------- | ------------ | ------------------------------------------------------------ | -------------------------- |\n",
    "| object         | str or mixed | string_, unicode_, mixed types                               | 文本或者混合数字           |\n",
    "| int64          | int          | int_, int8, int16, int32, int64, uint8, uint16, uint32, uint64 | 整型数字                   |\n",
    "| float64        | float        | float_, float16, float32, float64                            | 浮点数字                   |\n",
    "| bool           | bool         | bool_                                                        | True/False 布尔型          |\n",
    "| datetime64[ns] | nan          | datetime64[ns]                                               | 日期时间                   |\n",
    "| timedelta[ns]  | nan          | nan                                                          | 两个时间之间的距离，时间差 |\n",
    "| category       | nan          | nan                                                          | 有限文本值，枚举           |\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### pandas特有数据类型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### DatetimeTZDtype\n",
    "带有时区的日期时间格式。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "datetime64[ns, Asia/Shanghai]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    " pd.DatetimeTZDtype(\"ns\", tz='Asia/Shanghai')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也可以用字符串去指定类型，此字符串可用在所有指定数据类型的地方，所有数据类型道理一样。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0   2020-05-01 22:23:22.343200+08:00\n",
       "dtype: datetime64[ns, Asia/Shanghai]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Series(['20200501 22:23:22.3432'], dtype='datetime64[ns, Asia/Shanghai]')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0   2020-05-01 22:23:22.343200\n",
       "dtype: datetime64[ns]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Series(['20200501 22:23:22.3432'], dtype='datetime64[ns]') # 无时区"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果需要指定一个时间定值，可以用 pd.Timestamp():"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Timestamp('2017-01-01 12:00:00')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用字符形式\n",
    "pd.Timestamp('2017-01-01T12')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "# 用 datetime.datetime 的方法\n",
    "pd.Timestamp(2017, 1, 1, 12)\n",
    "# Timestamp('2017-01-01 12:00:00')\n",
    "pd.Timestamp(year=2017, month=1, day=1, hour=12)\n",
    "# Timestamp('2017-01-01 12:00:00')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### CategoricalDtype\n",
    "定义一个有限的字符枚举类型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CategoricalDtype(categories=['male', 'female'], ordered=True)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.CategoricalDtype(categories=['male', 'female'], ordered=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### PeriodDtype\n",
    "支持时间周期"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "period[D]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.PeriodDtype(freq='D') # 按天"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "period[M]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.PeriodDtype(freq=pd.offsets.MonthEnd()) # 按月，最后一天"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 数据类型的检测\n",
    "可以使用类型测试数据的类型：\n",
    "pd.api.types.is_bool_dtype(s)  \n",
    "pd.api.types.is_categorical_dtype(s)  \n",
    "pd.api.types.is_datetime64_any_dtype(s)  \n",
    "pd.api.types.is_datetime64_ns_dtype(s)  \n",
    "pd.api.types.is_datetime64_dtype(s)  \n",
    "pd.api.types.is_float_dtype(s)  \n",
    "pd.api.types.is_int64_dtype(s)  \n",
    "pd.api.types.is_numeric_dtype(s)  \n",
    "pd.api.types.is_object_dtype(s)  \n",
    "pd.api.types.is_string_dtype(s)  \n",
    "pd.api.types.is_timedelta64_dtype(s)  \n",
    "pd.api.types.is_bool_dtype(s)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 构建一个DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "index = pd.Index(data=[\"Tom\", \"Bob\", \"Mary\", \"James\"], name=\"name\")\n",
    "data = {\n",
    "    \"age\": [18, 30, 25, 40],\n",
    "    \"city\": [\"BeiJing\", \"ShangHai\", \"GuangZhou\", \"ShenZhen\"]\n",
    "}\n",
    "user_info = pd.DataFrame(data=data, index=index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 查看数据及其类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>city</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>name</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18</td>\n",
       "      <td>BeiJing</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30</td>\n",
       "      <td>ShangHai</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25</td>\n",
       "      <td>GuangZhou</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40</td>\n",
       "      <td>ShenZhen</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       age       city\n",
       "name                 \n",
       "Tom     18    BeiJing\n",
       "Bob     30   ShangHai\n",
       "Mary    25  GuangZhou\n",
       "James   40   ShenZhen"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.frame.DataFrame"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(user_info)  # pandas.core.frame.DataFrame"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 查看某列数据及其类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "Bob      30\n",
       "Mary     25\n",
       "James    40\n",
       "Name: age, dtype: int64"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(user_info.age)  # pandas.core.series.Series"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 查看某行数据及其类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "age          18\n",
       "city    BeiJing\n",
       "Name: Tom, dtype: object"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_info.loc['Tom', :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(user_info.loc['Tom', :])  # pandas.core.series.Series"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第3部分：Series"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Series**是一个带有**名称**和**索引**的一维数组，但与传统数组中元素类型必须相同不一样的是，Series中的元素类型可以不同，在**Series**中包含的数据类型可以是整数、浮点、字符串、Python对象等，这一点与Python中的列表比较类似，但与列表不同的是，列表只能通过数字索引取值，而**Series**可以通过自定义索引取值，从这一点来看**Series**与字典类似。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pandas.Series(data=None, index=None, dtype=None, name=None, copy=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "参数解释：\n",
    "- data：支持以下数据类型：\n",
    " - Python 字典\n",
    " - 多维数组\n",
    " - 标量值（如，5）\n",
    "- index：索引，类似数组或列表，值必须是可哈希的，并且与“data”具有相同的长度。允许使用非唯一索引值。将默认为RangeIndex（0，1，2，…，n）（如果未提供）。如果Index和字典同时提供，index将会覆盖字典的keys。\n",
    "- dtype: str，numpy.d类型，或ExtensionType，可选输出序列的数据类型。如果未指定，则将从“data”推断。\n",
    "- name：Series的名称。\n",
    "- copy: bool，默认为False,是否对输入数据进行复制。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. Series的创建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 方式一：通过列表或数组方式创建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    18\n",
       "1    30\n",
       "2    25\n",
       "3    40\n",
       "dtype: int64"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age = pd.Series(data=[18, 30, 25, 40])\n",
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "Bob      30\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.index = [\"Tom\", \"Bob\", \"Mary\", \"James\"] # 加索引\n",
    "user_age.index.name = \"name\"  # 索引加名字\n",
    "user_age.name=\"user_age_info\"  # series加名字\n",
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18\n",
       "Bob      30\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age = pd.Series(data=[18, 30, 25, 40], index=[\"Tom\", \"Bob\", \"Mary\", \"James\"], name='user_age_info')\n",
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 方式二：通过字典方式创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18\n",
       "Bob      30\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = {\"Tom\": 18, \"Bob\": 30, \"Mary\": 25, \"James\": 40}\n",
    "user_age = pd.Series(data=data, name=\"user_age_info\")\n",
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**注意**：data 为字典，且未设置 index 参数时，如果 Python 版本 >= 3.6 且 Pandas 版本 >= 0.23，Series 按字典的插入顺序排序索引。\n",
    "\n",
    "Python < 3.6 或 Pandas < 0.23，且未设置 index 参数时，Series 按字母顺序排序字典的键（key）列表。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**手动指定数据类型**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "James    40.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = {\"Tom\": 18, \"Bob\": 30, \"Mary\": 25, \"James\": 40}\n",
    "user_age = pd.Series(data=data, name=\"user_age_info\", dtype=float)\n",
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 方式三：通过标量值创建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "data 是标量值时，必须提供索引。Series 按索引长度重复该标量值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a    5.0\n",
       "b    5.0\n",
       "c    5.0\n",
       "d    5.0\n",
       "e    5.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Series(5., index=['a', 'b', 'c', 'd', 'e'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查看Series所有属性和方法**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Bob', 'James', 'Mary', 'T', 'Tom', 'abs', 'add', 'add_prefix', 'add_suffix', 'agg', 'aggregate', 'align', 'all', 'any', 'append', 'apply', 'argmax', 'argmin', 'argsort', 'array', 'asfreq', 'asof', 'astype', 'at', 'at_time', 'attrs', 'autocorr', 'axes', 'backfill', 'between', 'between_time', 'bfill', 'bool', 'clip', 'combine', 'combine_first', 'compare', 'convert_dtypes', 'copy', 'corr', 'count', 'cov', 'cummax', 'cummin', 'cumprod', 'cumsum', 'describe', 'diff', 'div', 'divide', 'divmod', 'dot', 'drop', 'drop_duplicates', 'droplevel', 'dropna', 'dtype', 'dtypes', 'duplicated', 'empty', 'eq', 'equals', 'ewm', 'expanding', 'explode', 'factorize', 'ffill', 'fillna', 'filter', 'first', 'first_valid_index', 'floordiv', 'ge', 'get', 'groupby', 'gt', 'hasnans', 'head', 'hist', 'iat', 'idxmax', 'idxmin', 'iloc', 'index', 'infer_objects', 'interpolate', 'is_monotonic', 'is_monotonic_decreasing', 'is_monotonic_increasing', 'is_unique', 'isin', 'isna', 'isnull', 'item', 'items', 'iteritems', 'keys', 'kurt', 'kurtosis', 'last', 'last_valid_index', 'le', 'loc', 'lt', 'mad', 'map', 'mask', 'max', 'mean', 'median', 'memory_usage', 'min', 'mod', 'mode', 'mul', 'multiply', 'name', 'nbytes', 'ndim', 'ne', 'nlargest', 'notna', 'notnull', 'nsmallest', 'nunique', 'pad', 'pct_change', 'pipe', 'plot', 'pop', 'pow', 'prod', 'product', 'quantile', 'radd', 'rank', 'ravel', 'rdiv', 'rdivmod', 'reindex', 'reindex_like', 'rename', 'rename_axis', 'reorder_levels', 'repeat', 'replace', 'resample', 'reset_index', 'rfloordiv', 'rmod', 'rmul', 'rolling', 'round', 'rpow', 'rsub', 'rtruediv', 'sample', 'searchsorted', 'sem', 'set_axis', 'shape', 'shift', 'size', 'skew', 'slice_shift', 'sort_index', 'sort_values', 'squeeze', 'std', 'sub', 'subtract', 'sum', 'swapaxes', 'swaplevel', 'tail', 'take', 'to_clipboard', 'to_csv', 'to_dict', 'to_excel', 'to_frame', 'to_hdf', 'to_json', 'to_latex', 'to_list', 'to_markdown', 'to_numpy', 'to_period', 'to_pickle', 'to_sql', 'to_string', 'to_timestamp', 'to_xarray', 'transform', 'transpose', 'truediv', 'truncate', 'tz_convert', 'tz_localize', 'unique', 'unstack', 'update', 'value_counts', 'values', 'var', 'view', 'where', 'xs']\n"
     ]
    }
   ],
   "source": [
    "print([attr for attr in dir(user_age) if not attr.startswith('_')])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Series属性"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Series常见的属性包含：\n",
    "- shape: Series的形状\n",
    "- index: Series的索引\n",
    "- values: Series的数据值。ndarray类型\n",
    "- name: Series的名称\n",
    "- dtype: Series的数据类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4,)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['Tom', 'Bob', 'Mary', 'James'], dtype='object')"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([18., 30., 25., 40.])"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'user_age_info'"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('float64')"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.dtype"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对于一个Series，其中最常用的属性为**值（values），索引（index），名字（name），类型（dtype）。**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. Series的方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.1 基本方法\n",
    "\n",
    "- head(n): 查看Series的前n个元素，默认n为5。\n",
    "- tail(n): 查看Series的后n个元素，默认n为5。\n",
    "- unique(): 返回Series中不重复的元素。\n",
    "- nunique(dropna=False)：返回Series中不重复的元素个数。\n",
    "- isna(): 判断元素是否是缺失值。\n",
    "- isnull(): 和isna()功能相同。\n",
    "- dropna(inplace=False)：删除缺失值。\n",
    "- isin(values)：成员运算，values为set或者list-like类型，判断series中每个元素是否是values的成员。\n",
    "- sort_index(ascending=False, inplace=False): 对索引排序\n",
    "- sort_values(ascending=False, inplace=False)：对值排序。\n",
    "- idmax(): 返回最大值的索引。\n",
    "- idmin(): 返回最小值的索引。\n",
    "- nlargest(): 返回n个最大的值。\n",
    "- nsmallest(): 返回n个最小的值。\n",
    "- count(): 返回非缺失值元素个数。\n",
    "- value_counts(ascending=False,dropna=True)：统计数据频率。\n",
    "- clip(lower, upper, inplace=False): 对Series在lower-upper范围进行截断，小于lower的替换为lower,大于upper的替换为upper。\n",
    "- replace(to_replace, value=None, inplace=False): 对Series中指定值进行替换。\n",
    "- where(cond, other=np.nan, inplace=False)： 对不满足cond的元素替换为other。\n",
    "- add_prefix(prefix): 统一加前缀。\n",
    "- add_suffix(suffix): 统一加后缀。\n",
    "- reset_index(drop=False, name=None, inplace=False): 重置索引，当drop为False时返回DataFrame。\n",
    "- to_frame(name=None):将Series转换为DataFrame。\n",
    "- append(to_append, ignore_index=False, verify_integrity=False)：将两个Series进行合并。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**创建数据表**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Ming     40.0\n",
       "Rose      NaN\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age = pd.Series(data=[18, 30, 25, 40, 81, 40, None], index=[\"Tom\", \"Bob\", \"Mary\", \"James\", \"Kobe\", \"Ming\", \"Rose\"], name='user_age_info')\n",
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.1 查看前（后）n个元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查看前5个元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查看后5个元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Mary     25.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Ming     40.0\n",
       "Rose      NaN\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**指定查看个数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom     18.0\n",
       "Bob     30.0\n",
       "Mary    25.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Kobe    81.0\n",
       "Ming    40.0\n",
       "Rose     NaN\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.tail(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.2 查看数据的基本信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "count     6.000000\n",
       "mean     39.000000\n",
       "std      22.289011\n",
       "min      18.000000\n",
       "25%      26.250000\n",
       "50%      35.000000\n",
       "75%      40.000000\n",
       "max      81.000000\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.describe()  # 查看Series基本统计信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "count     6.000000\n",
       "mean     39.000000\n",
       "std      22.289011\n",
       "min      18.000000\n",
       "5%       19.750000\n",
       "25%      26.250000\n",
       "50%      35.000000\n",
       "75%      40.000000\n",
       "95%      70.750000\n",
       "max      81.000000\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.describe(percentiles=[.05, .25, .75, .95]) # 可以自己选择分位数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.count()  # 查看非缺失值元素个数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.3 数据去重"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查看所有用户不重复的年龄**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([18., 30., 25., 40., 81., nan])"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.unique()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查看所有用户不重复的年龄个数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.nunique()  # 默认不包含缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.nunique(dropna=False)  # 包含缺失值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.4 删除缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      False\n",
       "Bob      False\n",
       "Mary     False\n",
       "James    False\n",
       "Kobe     False\n",
       "Ming     False\n",
       "Rose      True\n",
       "Name: user_age_info, dtype: bool"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.isna()     # 查看元素是否是缺失值\n",
    "# user_age.isnull()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Ming     40.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.dropna()  # 删除缺失值，返回删除后的结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Ming     40.0\n",
       "Rose      NaN\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age  # 默认不修改原始数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Ming     40.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.dropna(inplace=True)  # 在原始数据的基础上删除缺失值，可以设置inplace参数为True\n",
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.5 成员运算"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查看用户的年龄是否小于60**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom       True\n",
       "Bob       True\n",
       "Mary      True\n",
       "James     True\n",
       "Kobe     False\n",
       "Ming      True\n",
       "Name: user_age_info, dtype: bool"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.isin(list(range(60)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.6 排序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**对用户名进行排序**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.sort_index()  # 默认升序，从小到大"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Ming     40.0\n",
       "Mary     25.0\n",
       "Kobe     81.0\n",
       "James    40.0\n",
       "Bob      30.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.sort_index(ascending=False)  # 逆序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Ming     40.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age   # 原始数据并未修改"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.sort_index(inplace=True)  # 修改原始数据\n",
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**对年龄进行排序**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tom      18.0\n",
       "Mary     25.0\n",
       "Bob      30.0\n",
       "James    40.0\n",
       "Ming     40.0\n",
       "Kobe     81.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.sort_values()  # 默认升序，从小到大"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Kobe     81.0\n",
       "Ming     40.0\n",
       "James    40.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.sort_values(ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.7 统计数据频率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "40.0    2\n",
       "18.0    1\n",
       "25.0    1\n",
       "81.0    1\n",
       "30.0    1\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.value_counts()  # 不包含缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.count()  # 查看非缺失值个数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.8 获取最大(小)值及其索引"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**idxmax函数返回最大值所在索引，当存在多个最大值时，返回第一个最大值的索引，idxmin功能类似**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Kobe'"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.idxmax()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**nlargest函数返回前几个大的元素值，nsmallest功能类似**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Kobe     81.0\n",
       "James    40.0\n",
       "Ming     40.0\n",
       "Bob      30.0\n",
       "Mary     25.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.nlargest()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Kobe     81.0\n",
       "James    40.0\n",
       "Ming     40.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.nlargest(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.9 对元素值进行替换"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**clip是对超过或者低于某些值的数进行截断和补齐**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     40.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      20.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.clip(20,40)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**replace是对某些值进行替换**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.replace(20, 30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      25.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.replace([18, 20], [25, 30])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      25.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.replace({18: 25, 20: 30})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**where 将不满足条件的元素替换为指定值,默认为np.nan**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob       NaN\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary      NaN\n",
       "Ming     40.0\n",
       "Tom       NaN\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.where(user_age > 30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     30.0\n",
       "Ming     40.0\n",
       "Tom      30.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.where(user_age > 30, 30)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.10 应用函数 `/`元素迭代"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      31.0\n",
       "James    41.0\n",
       "Kobe     82.0\n",
       "Mary     26.0\n",
       "Ming     41.0\n",
       "Tom      19.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.add(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      31.0\n",
       "James    41.0\n",
       "Kobe     82.0\n",
       "Mary     26.0\n",
       "Ming     41.0\n",
       "Tom      19.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age + 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      31.0\n",
       "James    41.0\n",
       "Kobe     82.0\n",
       "Mary     26.0\n",
       "Ming     41.0\n",
       "Tom      19.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.apply(lambda x: x + 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      3.0\n",
       "James    6.0\n",
       "Kobe     5.0\n",
       "Mary     5.0\n",
       "Ming     6.0\n",
       "Tom      5.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.apply(lambda x: x % 7 + 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.11 统一添加前/后缀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "user-Bob      30.0\n",
       "user-James    40.0\n",
       "user-Kobe     81.0\n",
       "user-Mary     25.0\n",
       "user-Ming     40.0\n",
       "user-Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.add_prefix('user-')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob-age      30.0\n",
       "James-age    40.0\n",
       "Kobe-age     81.0\n",
       "Mary-age     25.0\n",
       "Ming-age     40.0\n",
       "Tom-age      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.add_suffix('-age')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.12 Series转为DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>index</th>\n",
       "      <th>user_age_info</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Bob</td>\n",
       "      <td>30.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>James</td>\n",
       "      <td>40.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Kobe</td>\n",
       "      <td>81.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Mary</td>\n",
       "      <td>25.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Ming</td>\n",
       "      <td>40.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Tom</td>\n",
       "      <td>18.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   index  user_age_info\n",
       "0    Bob           30.0\n",
       "1  James           40.0\n",
       "2   Kobe           81.0\n",
       "3   Mary           25.0\n",
       "4   Ming           40.0\n",
       "5    Tom           18.0"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 方法1：重置索引，索引转换为新的一列，默认列名为index\n",
    "user_age.reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>user_age_info</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>Bob</th>\n",
       "      <td>30.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>James</th>\n",
       "      <td>40.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Kobe</th>\n",
       "      <td>81.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Mary</th>\n",
       "      <td>25.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Ming</th>\n",
       "      <td>40.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Tom</th>\n",
       "      <td>18.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       user_age_info\n",
       "Bob             30.0\n",
       "James           40.0\n",
       "Kobe            81.0\n",
       "Mary            25.0\n",
       "Ming            40.0\n",
       "Tom             18.0"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 方式2：to_frame\n",
    "user_age.to_frame()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3.1.13 Series合并"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "张三    21.0\n",
       "李四    30.0\n",
       "王五    40.0\n",
       "Name: user_age_info2, dtype: float64"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age2 = pd.Series(data={\"张三\": 21, \"李四\": 30, \"王五\": 40}, name=\"user_age_info2\", dtype=float)\n",
    "user_age2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "张三       21.0\n",
       "李四       30.0\n",
       "王五       40.0\n",
       "dtype: float64"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.append(user_age2)  # 返回合并之后的Series"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     25.0\n",
       "Ming     40.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age  # 不修改自身"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.2 数字类型方法\n",
    "\n",
    "- max(): 最大值\n",
    "- min(): 最小值\n",
    "- sum(): 和\n",
    "- var(): 方差\n",
    "- std(): 标准差\n",
    "- median(): 中位数\n",
    "- mean(): 平均值\n",
    "- mad(): 平均绝对偏差,每个数据点与平均值之间的平均距离。\n",
    "- abs(): 绝对值\n",
    "- quantile(): 分位数函数\n",
    "- cummax(): 累计最大值\n",
    "- cumsum(): 累计和\n",
    "- cumprod(): 累计乘积\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "81.0"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.max()   # 最大值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18.0"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.min()  # 最小值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "234.0"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.sum()   # 和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "496.8"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.var()    # 方差"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "22.289010745208053"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.std()   # 标准差"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "35.0"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.median()  # 中位数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "39.0"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.mean()  # 平均值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14.666666666666666"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.mad()   # 平均绝对偏差"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "35.0"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.quantile()  # 默认q=0.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "26.25"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.quantile(0.25)  # 指定q"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    40.0\n",
       "Kobe     81.0\n",
       "Mary     81.0\n",
       "Ming     81.0\n",
       "Tom      81.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.cummax()  # 累计最大值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      30.0\n",
       "James    30.0\n",
       "Kobe     30.0\n",
       "Mary     25.0\n",
       "Ming     25.0\n",
       "Tom      18.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.cummin()  # 累计最小值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob       30.0\n",
       "James     70.0\n",
       "Kobe     151.0\n",
       "Mary     176.0\n",
       "Ming     216.0\n",
       "Tom      234.0\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.cumsum()  # 累计和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Bob      3.000000e+01\n",
       "James    1.200000e+03\n",
       "Kobe     9.720000e+04\n",
       "Mary     2.430000e+06\n",
       "Ming     9.720000e+07\n",
       "Tom      1.749600e+09\n",
       "Name: user_age_info, dtype: float64"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.cumprod()  # 连乘积"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.3 字符串类型方法\n",
    "\n",
    "pandas中字符串类型Series通过Series.str.方法进行调用，常用的方法如下：\n",
    "\n",
    "![字符串类型方法](https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python/blog/%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%96%B9%E6%B3%95.png)\n",
    "\n",
    "\n",
    "通过以上我们可以知道，pandas中字符串Series几乎具有Python字符串所有的功能，从这里就可以看出pandas的强大之处了。\n",
    "关于字符串类型的方法，我们将在之后文本数据处理章节中进行介绍。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.4 分类数据方法\n",
    "分类数据直白来说就是取值为有限的，或者说是固定数量的可能值。例如：性别、血型，通过Series.cat.方法名来调用。具体使用将在后面分类数据处理章节进行详细介绍。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.5 时间序列数据方法\n",
    "关于时间数据类型，pandas中也对其有针对性的处理方法。时间数据类型通过Series.dt.方法名来调用。具体使用将在后面时间数据处理章节进行详细介绍。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3.6 画图\n",
    "\n",
    "Series.plot(参数)，参数如下:\n",
    "![plot参数](https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python/blog/series_plot.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "官方文档：http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. Series的增删改查"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4.1 访问数据元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "访问Series数据元素有3种方式：\n",
    "- 索引\n",
    "- 序号\n",
    "- 布尔"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**创建一个Series**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "Bob      30\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "name = pd.Index([\"Tom\", \"Bob\", \"Mary\", \"James\"], name=\"name\")\n",
    "user_age = pd.Series(data=[18, 30, 25, 40], index=name, name=\"user_age_info\")\n",
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**按索引查找**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**按索引查找单个指定元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.Tom  # 点访问属性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age['Tom']  # 取索引值为Tom的元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.get('Tom')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [],
   "source": [
    "# user_age['Kobe']  # 会报错\n",
    "user_age.get('Kobe')  # get方式不会报错"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "30"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.get('Kobe', default=30)  # 不存在的key可以设置默认值b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**按索引数组查找多个元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age[['Tom', 'James']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "Bob      30\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**按序号查找**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**按序号查找指定元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age[0]  # 第一个元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**按序号数组查找多个元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Bob      30\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age[[1,3]]  # 查找序号为1和3的数据元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**按序号切片查找多个元素**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom     18\n",
       "Bob     30\n",
       "Mary    25\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age[:3]   # 查找前3个元素，即序号为0,1,2的元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**布尔查找**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age[user_age > 30] # 查找所有年龄大于30的元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4.2 添加数据元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pandas中添加数据元素的方法与字典类似，可以直接通过`[索引] = value`进行添加。如果想要添加多个元素，可以将其转换为Series，采用上面介绍的append方法对其进行合并。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "Bob      30\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_age['Wade'] = 39\n",
    "user_age['Michael'] = 50"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom        18\n",
       "Bob        30\n",
       "Mary       25\n",
       "James      40\n",
       "Wade       39\n",
       "Michael    50\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4.3 修改数据元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pandas的Series对数据元素进行修改，可以直接使用`Series[索引/序号] = new_value`zip样的方式。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_age['Wade'] = 38  # 按索引修改"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom        18\n",
       "Bob        30\n",
       "Mary       25\n",
       "James      40\n",
       "Wade       38\n",
       "Michael    50\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 106,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "30"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_age[1] = 35  # 按序号修改"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom        18\n",
       "Bob        35\n",
       "Mary       25\n",
       "James      40\n",
       "Wade       38\n",
       "Michael    50\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4.4 删除数据元素"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pandas中想要删除Series的数据元素，我们可以采用`del Series[索引]`这样的方法，当然，也可以使用内置的drop方法对其进行删除。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [],
   "source": [
    "del user_age['Wade']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom        18\n",
       "Bob        35\n",
       "Mary       25\n",
       "James      40\n",
       "Michael    50\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "Bob      35\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age.drop('Michael')   # 不会改变原始数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom        18\n",
       "Bob        35\n",
       "Mary       25\n",
       "James      40\n",
       "Michael    50\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 113,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_age.drop('Michael', inplace=True)   # 改变原始数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Tom      18\n",
       "Bob      35\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_age.drop(['Tom', 'Bob'], inplace=True)   # 一次性删除多个元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "name\n",
       "Mary     25\n",
       "James    40\n",
       "Name: user_age_info, dtype: int64"
      ]
     },
     "execution_count": 117,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_age"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 简单小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本节内容到这里就结束了，本节第1部分首先带大家了解了pandas的主要应用场景及特点；第2部分主要介绍了pandas的两种基本数据结构，Series和DataFram的特点及基本使用方法。第3部分针对Series这种数据结构进行详细的介绍，分别从Series的创建、属性、方法和增删改查四个方面进行说明。如果你认真学习了以上内容，相信你已经对pandas有了一个初步的了解，并已经掌握了Series的基本使用。下一节将介绍pandas第二大数据结构DataFrame，继续加油，相信你学完这两种数据结构，将来无论面对如何复杂的情形，都会处乱不惊，心态就一个字：稳。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "320px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
